package cn.iocoder.yudao.module.erp.service.monthplaninfo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.erp.dal.dataobject.accountplanrecord.AccountPlanRecordDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.planinfo.PlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.mysql.planinfo.PlanInfoMapper;
import cn.iocoder.yudao.module.erp.enums.Constant;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import cn.iocoder.yudao.module.erp.controller.admin.monthplaninfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.monthplaninfo.MonthPlanInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.monthplaninfo.MonthPlanInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 月度计划 Service 实现类
 *
 * @author mhc
 */
@Service
@Validated
public class MonthPlanInfoServiceImpl implements MonthPlanInfoService {

    @Resource
    private MonthPlanInfoMapper monthPlanInfoMapper;

    @Resource
    private PlanInfoMapper planInfoMapper;

    @Override
    @Transactional
    public Long createMonthPlanInfo(MonthPlanInfoSaveReqVO createReqVO) {
        // 插入
        MonthPlanInfoDO monthPlanInfo = BeanUtils.toBean(createReqVO, MonthPlanInfoDO.class);
        //计算每日
        //批量插入每日计划
        //每日管容
        Date strat=DateUtil.date(createReqVO.getBeginTime());
        Date end=DateUtil.date(createReqVO.getEndTime());
        long dayDiff=DateUtil.between(strat,end, DateUnit.DAY)+1;
        BigDecimal saleGasAllCount=monthPlanInfo.getCapacityTotal();
        BigDecimal avg=saleGasAllCount.divide(new BigDecimal(dayDiff),4, BigDecimal.ROUND_HALF_UP);
        monthPlanInfo.setCapacityDay(avg);
        monthPlanInfo.setLineCost(new BigDecimal("0"));
        monthPlanInfo.setSaleAllCost(new BigDecimal("0"));
        monthPlanInfo.setBuyAllCost(new BigDecimal("0"));



       /* BigDecimal buyGasAllCount=monthPlanInfo.getBuyGasAllCount();
        BigDecimal buySub=buyGasAllCount.divide(new BigDecimal(dayDiff),4, BigDecimal.ROUND_HALF_UP);
        monthPlanInfo.setBuySubCount(buySub);

        monthPlanInfo.setBuyAllCount(new BigDecimal("0"));*/

        monthPlanInfoMapper.insert(monthPlanInfo);

        List<PlanInfoDO> list=new ArrayList<>();
        while (!strat.after(end)){
            PlanInfoDO planInfo=new PlanInfoDO();
            BeanUtils.copyProperties(monthPlanInfo,planInfo);
           // PlanInfoDO planInfo= BeanUtils.toBean(monthPlanInfo, PlanInfoDO.class);
            planInfo.setId(null);
            LocalDate localDate = strat.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            planInfo.setNowTime(localDate);
           /* planInfo.setCompanyId(SecurityFrameworkUtils.getLoginUserDeptId());*/
            planInfo.setCompanyId(monthPlanInfo.getId());
            //Integer type=monthPlanInfo.getCheckType();

            BigDecimal salePrice=monthPlanInfo.getSalePrice();

            planInfo.setSaleRealPrice(salePrice);
            planInfo.setLinePrice(monthPlanInfo.getLinePrice());

           /* planInfo.setBuyRealPrice(monthPlanInfo.getBuyPrice());*/

            planInfo.setBuySubCount(monthPlanInfo.getCapacityDay());
            planInfo.setSaleSubCount(monthPlanInfo.getCapacityDay());

            planInfo.setBuyRealPrice(monthPlanInfo.getBuyPrice());

            planInfo.setSaleRealPrice(monthPlanInfo.getSalePrice());

            planInfo.setStatus(0);

            //
            planInfo.setSaleBillStatus(0);
            planInfo.setSaleAccountStatus(0);
            planInfo.setBuyBillStatus(0);
            planInfo.setBuyAccountStatus(0);
            list.add(planInfo);
            strat=DateUtil.offsetDay(strat,1);
            //planInfoMapper.insert(planInfo);
        }
        if(list.size()>0){
            planInfoMapper.insertBatch(list);
        }

//        for(){
//
//        }
        // 返回
        return monthPlanInfo.getId();
    }

    @Override
    public void updateMonthPlanInfo(MonthPlanInfoUpdateReqVO updateReqVO) {
        // 校验存在
        //validateMonthPlanInfoExists(updateReqVO.getId());
        MonthPlanInfoDO old=monthPlanInfoMapper.selectById(updateReqVO.getId());
        if (old == null) {
            throw exception(MONTH_PLAN_INFO_NOT_EXISTS);
        }

        // 更新
        MonthPlanInfoDO updateObj = BeanUtils.toBean(updateReqVO, MonthPlanInfoDO.class);

        BeanUtil.copyProperties(updateReqVO,old, CopyOptions.create().ignoreNullValue());


        Date strat=DateUtil.date(old.getBeginTime());
        Date end=DateUtil.date(old.getEndTime());
        long dayDiff=DateUtil.between(strat,end, DateUnit.DAY)+1;
        BigDecimal saleGasAllCount=updateObj.getCapacityTotal();
        BigDecimal avg=saleGasAllCount.divide(new BigDecimal(dayDiff),4, BigDecimal.ROUND_HALF_UP);
        updateObj.setCapacityDay(avg);



        monthPlanInfoMapper.updateById(updateObj);
    }

    @Override
    @Transactional
    public void deleteMonthPlanInfo(Long id) {
        // 校验存在
        validateMonthPlanInfoExists(id);

        //得到数据
        Long exist=planInfoMapper.selectCount(new LambdaQueryWrapperX<PlanInfoDO>().eq(PlanInfoDO::getCompanyId,id).ne(PlanInfoDO::getStatus,"0"));
        if(exist>0){
            throw exception(new ErrorCode(1_000_000_000, "存在已结算的日计划，不可删除"));
        }else{
            //删除日计划
            planInfoMapper.delete(new LambdaQueryWrapperX<PlanInfoDO>().eq(PlanInfoDO::getCompanyId,id));
            // 删除
            monthPlanInfoMapper.deleteById(id);
        }

    }

    private void validateMonthPlanInfoExists(Long id) {
        if (monthPlanInfoMapper.selectById(id) == null) {
            throw exception(MONTH_PLAN_INFO_NOT_EXISTS);
        }
    }

    @Override
    public MonthPlanInfoDO getMonthPlanInfo(Long id) {
        return monthPlanInfoMapper.selectById(id);
    }

    @Override
    public PageResult<MonthPlanInfoDO> getMonthPlanInfoPage(MonthPlanInfoPageReqVO pageReqVO) {
        return monthPlanInfoMapper.selectPage(pageReqVO);
    }

}